package com.wxmit.module.system.service.impl;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.wxmit.module.system.domain.SysDictData;
import com.wxmit.module.system.domain.SysDictType;
import com.wxmit.module.system.mapper.SysDictTypeMapper;
import com.wxmit.module.system.service.ISysDictDataService;
import com.wxmit.module.system.service.ISysDictTypeService;
import com.wxmit.system.base.core.ShushanServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 字典类型Service业务层处理
 * 
 * @author xiong
 * @date 2022-08-09
 */
@Service
public class SysDictTypeServiceImpl extends ShushanServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService
{
    @Autowired
    private SysDictTypeMapper sysDictTypeMapper;

    @Autowired
    private ISysDictDataService sysDictDataService;


    @Override
    public List<SysDictType> getList(SysDictType searchData) {
        return sysDictTypeMapper.getList(searchData);
    }

    @Override
    public boolean save(SysDictType entity) {
        checkUnion(entity);
        return super.save(entity);
    }

    @Override
    public boolean updateById(SysDictType entity) {
        checkUnion(entity);
        return super.updateById(entity);
    }

    @Override
    public boolean removeTypeByIds(List<Long> dictIds) {
        List<SysDictType> sysDictTypes = sysDictTypeMapper.selectBatchIds(dictIds);
        Set<String> collect = sysDictTypes.stream().map(SysDictType::getType).collect(Collectors.toSet());
        long count = sysDictDataService.count(new LambdaQueryWrapper<SysDictData>().in(SysDictData::getType, collect));
        Assert.isTrue(count == 0,"存在字典数据，无法对字典类别进行删除！");
        return removeByIds(dictIds);
    }

    public void checkUnion(SysDictType entity){
        LambdaQueryChainWrapper<SysDictType> lambdaQuery = lambdaQuery();
        lambdaQuery.eq(SysDictType::getType,entity.getType());
        if(Objects.nonNull(entity.getId())){
            lambdaQuery.ne(SysDictType::getId,entity.getId());
        }
        Assert.isTrue(lambdaQuery.count() == 0L,"字典类型不能重复！");
    }

}